Hallo All.
I have a quick question that tickles me. Its about operator overloading in Classes. I will demonstrate with a code snippet. I hope that someone will be able to clear it up a bit for me.
<snip>
Code:
class rectangle {
// Rectangle Object, used to store the length and width of a rect
// and compute it's area. Set functions included.
private:
float itsLength; // Rectangle length
float itsWidth; // Rectangle width
public:
float getArea(); // function to get area of Rectangle
void setLength(float pLength); // function to set Length
void setWidth(float pWidth); // function to set Width
float operator+(rectangle &pRect); // The operator overloading function.
};
...
...
float rectangle::operator+(rectangle &pRect) {
return getArea() + pRect.itsLength * pRect.itsWidth; // This is just my demonstration. Normally it would not be done like this.
}
int main(int argc, char* argv[])
{
rectangle r1, r2; // Create 2 instances of class rectangle
r1.setLength(10); // Set r1's length to 10
r1.setWidth(5); // Set r1's width to 5
r2.setLength(5); // Set r2's length to 5
r2.setWidth(2); // Set r2's width to 2;
float total = r1 + r2; // Operator overloading comes into play.
cout << "Total == " << total; // print total to screen.
getch();
return 0;
}
</snip>
Now, it shoes clearly that in the function rectangle::operator+(rectangle &pRect) that I access the private members of the referenced object &pRect.
Altho this is a nice feature to have, doesn't it defeat the purpose of private members. I mean, private members are supposed to be private ? Or am I missing the point here ?
I would be greatful if anyone can please explain to me why this is possible, and if there is any specific reason for it being so :)
Thanks in advance.
Regards
PHaRaoH